﻿using Application.Common.Interfaces;
using Application.Features.Roles.EventHandlers;
using Common.Attributes;
using Domain.Entities.Identity;
using MediatR;
using Microsoft.EntityFrameworkCore;
using System.ComponentModel;

namespace Application.Features.Menus.Commands.Delete;

/// <summary>
/// 删除菜单
/// </summary>
[Description("删除")]
[GroupDescription("菜单管理")]
public class DeleteMenuCommand : IRequest<bool>
{
    /// <summary>
    /// 唯一标识
    /// </summary>
    [Description("唯一标识")]
    public List<long> MenuIds { get; set; }
}

/// <summary>
/// 处理程序
/// </summary>
public class DeleteMenuCommandHandler : IRequestHandler<DeleteMenuCommand, bool>
{
    private readonly IApplicationDbContext _context;
    private readonly IMediator _mediator;

    public DeleteMenuCommandHandler(
        IApplicationDbContext context, IMediator mediator)
    {
        _context = context;
        _mediator = mediator;
    }

    /// <summary>
    /// 业务逻辑
    /// </summary>
    /// <param name="request">请求参数</param>
    /// <param name="cancellationToken">取消标记</param>
    /// <returns>返回处理结果</returns>
    public async Task<bool> Handle(DeleteMenuCommand request, CancellationToken cancellationToken)
    {
        var menusToDelete = await _context.Menus
            .Include(rm=>rm.RoleMenus)
                 .ThenInclude(r=>r.Role)
                      .ThenInclude(ur=>ur.UserRoles)
                              .ThenInclude(u=>u.User)
            .Where(x => request.MenuIds.Contains(x.Id))
            .ToListAsync();

        if (menusToDelete.Any()) 
        {
            var usersRelatedToMenus = menusToDelete
                .SelectMany(menu => menu.RoleMenus.Select(roleMenu => roleMenu.Role))
                .SelectMany(role => role.UserRoles.Select(userRole => userRole.User))
                .ToHashSet();

            await _mediator.Publish(new DeleteMenuEvent<HashSet<User>>(usersRelatedToMenus));
            _context.Menus.RemoveRange(menusToDelete);
        }

        return true;
    }
}